package com.houger.ddd.datamanager.entity;

import cn.hutool.core.lang.Assert;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Getter
public class InventoryId implements Serializable {

    private final Map<String,Serializable> args = new HashMap<String,Serializable>();

    public InventoryId() {

    }

    public InventoryId(Serializable id) {
        setId(id);
    }

    public InventoryId setId(Serializable id){
        args.put("id",id);
        return this;
    }

    public InventoryId addProperties(String name, Serializable val){
        args.put(name,val);
        return this;
    }

    public Long getId(){
        return getLong("id");
    }

    public Long getLong(String name){
        return Long.valueOf(String.valueOf(this.args.get(name)));
    }

    public String getString(String name){
        return String.valueOf(this.args.get(name));
    }

    @Override
    public String toString(){
        Assert.isFalse(args.isEmpty());
        StringBuilder sb = new StringBuilder();
        final ArrayList<String> keyList = new ArrayList<>(args.keySet());
        //key按字典排序，防止顺序错误
        Collections.sort(keyList);
        for (String key : keyList) {
            sb.append(key).append('=').append(args.get(key)).append('&');
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }

    public static InventoryId parse(String idKeys){
        Assert.isTrue(StringUtils.isNotEmpty(idKeys));
        InventoryId inventoryId = new InventoryId();
        final String[] props = idKeys.split("&");
        for (String prop : props) {
            final String[] strs = prop.split("=");
            inventoryId.addProperties(strs[0].trim(),strs[1].trim());
        }
        return inventoryId;
    }

}
